# -*- coding: UTF-8 -*-
import url_manager, html_downloader, html_outputer, html_parser
import traceback

class SpiderMain(object):

    def __init__(self):
        self.urls = url_manager.UrlManager()
        self.downloader = html_downloader.HtmlDownloader()
        self.parser = html_parser.HtmlParser()
        self.output = html_outputer.HtmlOutputer()

    def craw(self, root_url,PAGE,ROW):
        count = 1

        self.urls.add_new_url(root_url)
        next_page = self.urls.next_page_url(root_url)
        self.urls.add_new_url(next_page)

        for i in range(1,PAGE):
            next_page = self.urls.next_page_url(next_page)
            self.urls.add_new_url(next_page)
        while self.urls.has_new_url():
            try:
                new_url = self.urls.get_new_url()
                print('craw %d : %s' % (count, new_url))

                html_cont = self.downloader.download(new_url)
                new_urls, new_data = self.parser.parse(new_url, html_cont)
                if new_urls:
                    self.urls.add_new_urls(new_urls)
                if new_data:
                    self.output.collect_data(new_data)
                if count == ROW:
                    break
            except Exception as e:
                traceback.print_exc()
                print(e)
            count = count + 1

        self.output.save_data()


if __name__ == "__main__":
    root_url = "https://list.jd.com/list.html?cat=1713,3287,3797&page=1&sort=sort_totalsales15_desc&trans=1&JL=6_0_0#J_main"

    PAGE = 5  #向后翻5页
    ROW = 300 #获取300条数据

    obj_spider = SpiderMain()
    obj_spider.craw(root_url,PAGE,ROW)
